# Title: 本地提单
# Params: text|multi_str|, account|one_str|wulongfei1
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2024/9/2 上午10:36
# @Author: wen
# @Email:happiness.sq@foxmail.com
# @README:
import base64
import json
import re
import socket
import requests
import warnings
import datetime
# 过滤特定警告
from urllib3.exceptions import InsecureRequestWarning

warnings.filterwarnings("ignore", message="Unverified HTTPS request", category=InsecureRequestWarning)


def parse_event_text(text, log):
    # 定义一部字典，用于存储解析出的字段
    parsed_data = {}

    # 使用正则表达式匹配字段和对应的值
    patterns = {
        "资产校验": r"资产校验[:：](.*)",  # 匹配字段和值，考虑可能的冒号和空格
        "产品名称": r"产品名称[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "事件产生时间": r"事件产生时间[:：](.*)",  # 匹配时间格式
        "资源池": r"资源池[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "问题主题": r"问题主题[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "事件描述": r"事件描述[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "维保状态": r"维保状态[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "一级部门": r"一级部门[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "二级部门": r"二级部门[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "事件一级分类": r"事件一级分类[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "事件二级分类": r"事件二级分类[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "事件三级分类": r"事件三级分类[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "关联工单编号": r"关联工单编号[:：](.*)",  # 匹配工单编号
        "事件问题来源": r"事件问题来源[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "影响业务系统": r"影响业务系统[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "优先级": r"优先级[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "联系人": r"联系人[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
        "联系人电话": r"联系人电话[:：](.*)",  # 匹配联系人电话
        "联系人邮箱": r"联系人邮箱[:：](.*)",  # 匹配邮箱
        "事件处理人": r"事件处理人[:：](.*)",  # 匹配字段和值，直到遇到空格或文本结尾
    }

    if '告警同步' in text:
        if no := re.search(patterns['关联工单编号'], text):
            if not no.group(1).strip():
                log(f"关联工单编号 ,未匹配到")
                log("程序退出")
                return
    else:
        del patterns['关联工单编号']

    for key, pattern in patterns.items():
        match = re.search(pattern, text)
        if not match:
            log(f"{key},未匹配到")
            return
        parsed_data[key] = match.group(1).strip()

    return parsed_data


def extract_sn(text):
    # 更新正则表达式以适应不同格式和空格
    pattern = r"SN\(序列号\)[：:]\s*([\w\d]+)"
    match = re.search(pattern, text)

    if match:
        # 提取并返回 SN(序列号) 的值
        return match.group(1).strip()
    else:
        return None


def is_port_open(host: str, port: int) -> bool:
    """检查指定的主机和端口是否开放"""
    with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
        sock.settimeout(3)  # 设置超时时间为 3 秒
        try:
            sock.connect((host, port))
            return True
        except (socket.timeout, socket.error):
            return False


class yun_ge:
    def __init__(self, log):
        """替换为自己的cookies,即可使用"""
        self.token = None
        self.log = log
        self.json_data = {}
        self.taskId = None
        self.headers = {
            "accept": "*/*",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "cache-control": "no-cache",
            "content-type": "application/json;charset=utf-8",
            "pragma": "no-cache",
            "sec-ch-ua": "\"Not A(Brand\";v=\"99\", \"Microsoft Edge\";v=\"121\", \"Chromium\";v=\"121\"",
            "sec-ch-ua-mobile": "?0",
            "sec-ch-ua-platform": "\"Windows\"",
            "sec-fetch-dest": "empty",
            "sec-fetch-mode": "cors",
            "sec-fetch-site": "same-origin",
            "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0"
        }
        self.urls = {
            '172.17.42.253': 28080,  # sdp_url
            '172.21.152.199': 10372,  # zw_url
            '10.217.241.40': 10372
        }
        self.url = self.find_open_url()
        if not self.url:
            self.log('网络连接失败，无法继续执行。请检查网络')
            return
        self.cookies = {
            "sso_t_name": "uniToken",
            "sso_t_value": "eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ7XCJpcFwiOlwiMTk3LjE2Ni4yMzQuMTI4XCIsXCJuYW1lXCI6XCLllJDluIVcIixcIm1vYmlsZVwiOlwiMTg4ODYwMjU0NzRcIixcImFjY291bnRcIjpcImR3dGFuZ3NodWFpXCIsXCJzdWJBY2NvdW50XCI6XCJkd3RhbmdzaHVhaVwifSIsIm5iZiI6MTcxMDQ2Njc5NywiaXNzIjoicG9ydGFsLXN0ZXdhcmQiLCJleHAiOjE3MTA0NjY4NTcsImlhdCI6MTcxMDQ2Njc5NywianRpIjoiOWVhZGFkM2E4ZmViNDQ0YmI5ZjM1Y2IyYzdlMmVhNTUifQ.q1CiKZOeD_7Kyvl9PbzOPmFkd7ObAYOXcRf8oYxq3SU"

        }
        today = datetime.datetime.now()
        self.date = today.strftime('%Y-%m-%d %H:%M:%S')
        self.next_day = (today + datetime.timedelta(days=20)).strftime('%Y-%m-%d %H:%M:%S')
        self.session = requests.Session()
        self.headers['authorization'] = "Bearer " + self.get_token()
        self.problem = None

    def find_open_url(self):
        """根据端口开放情况选择 URL"""
        for host, port in self.urls.items():
            if is_port_open(host, port):
                return f'{host}:{port}'
        return None

    def get_token(self):
        params = {
            "code": "SHA3RTNqSW95WGlOd0lNQXlSeEFGQT09",
            "service": "s",
            "type": "umsToken"
        }
        url = f"https://{self.url}/uc/sso/auth"
        for _ in range(1, 3):
            try:
                response = self.session.get(url, headers=self.headers, cookies=self.cookies, params=params,
                                            verify=False,
                                            timeout=10)
                if response.json()['token']:
                    self.log(f"{_account} 获取token成功")
                    return response.json()['token']
                else:
                    self.log("获取token失败")
                    return False
            except Exception as e:
                self.log(f"获取token失败，{e}")
                return False

    def submit_ticket(self, params, sjclrID):
        sn = extract_sn(params['事件描述'])
        if not sn:
            self.log('未找到sn')
            self.log('程序退出')
            return False
        # 获取当前时间
        now = datetime.datetime.now()

        # 格式化时间为指定的字符串格式
        formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")

        data = {
            "xtsjgzdx": {
                "sjxgfj": "",
                "sjyy": "",
                "zyglms": "",
                "fileName": "",
                "sjclbg": "",
                "ejfl": "",
                "zyc": f"{params['资源池']}",
                "sjms": f"{params['事件描述']}",
                "dealPerson": "",
                "changeHardwareType": "",
                "zrcs": "",
                "zcbh": "",
                "statusTime": "",
                "implement": "",
                "dealTimeLimit": "",
                "isChangeHardware": "",
                "solveScheme": "",
                "sheetTimehandl": "",
                "zcxyjgts": "",
                "ejbm": f"{params['二级部门']}",
                "sheetNo": "",
                "sheetReasonClass": "",
                "yjbm": f"{params['一级部门']}",
                "ywyxsz": "",
                "zcbhySNhsftc": "1",
                "sjyjfl": f"{params['事件一级分类']}",
                "sheetReasonClass2": "",
                "sheetReasonClass3": "",
                "ywzjID": "",
                "probID": "",
                "yxj": f"{params['优先级']}",
                "sjjjsj": "",
                "attachList2": "",
                "lxrID": "2211110010102092508",
                "sjxz": "",
                "glgdbh": "",
                "lxryx": "zhaowencheng@gz.chinamobile.com",
                "yjfl": "",
                "malfuntionCause": "",
                "czxgfj": "",
                "fileSize": "",
                "zt": f"{params['问题主题']}",
                "lxrzh": "zhaowencheng",
                "lxrdh": "18884901125",
                "sjejfl": "",
                "sjgdlx": "",
                "Predictresult1": "",
                "sjejflID": 26,
                "sheetProblemReason": "",
                "yjbmID": "6c1f1415-aa0d-11e9-995c-0242ac110002",
                "sheetOperation": "",
                "sjwtly": f"{params['事件问题来源']}",
                "ipdz": f"{params['资产校验'].split('(')[0]}",
                "lcgdlx": "",
                "sheetHandler": "",
                "cpfw": "",
                "gdbh": "",
                "sheetSsbg": "",
                "alarmId": "",
                "bz": "",
                "fileUrl": "",
                "sheetTransitionstate": "",
                "sjcssj": f"{params['事件产生时间']}",
                "sheetStatus": "",
                "sdywglryID": "",
                "sdywzgID": "",
                "sjclgcjjg": "",
                "sheetRuestionBasis": "",
                "orderID": "",
                "lxr": f"{params['事件处理人']}",
                "probSN": "",
                "sheetPlanOver": "",
                "attachList": "",
                "sfbm": "",
                "snh": f"{sn}",
                "sjwtfl": f"{params['事件二级分类']}",
                "changeNo": "",
                "zrdw": "",
                "sjyjflID": 12,
                "sjclr": f"{params['联系人']}",
                "sjdjsj": f"{formatted_time}",
                "yxywxt": f"{params['影响业务系统']}",
                # "sjclrID": "dwzhangzhixi",
                "sjclrID": f"{sjclrID}",
                "sheetId": "",
                "ywglryID": "",
                "sjsjfl": f"{params['事件三级分类']}",
                "sheetSolution": "",
                "sheetOpinion": "",
                "sub_rjwt": [],
                "sub_yjwt": [],
                "sub_yxywxt": [],
                "initData": {
                    "rjwt": {
                        "rjkfs": None,
                        "ptmc": None
                    },
                    "yjwt": {
                        "sbfl": None,
                        "cs": None,
                        "bj": None,
                        "sbxh": None,
                        "sblx": None,
                        "sb": None
                    },
                    "yxywxt": {
                        "ywxt": None,
                        "yjbm": None,
                        "ejbm": None
                    }
                }
            }
        }
        self.problem = params['问题主题']
        if params['事件问题来源'] == '告警同步':
            data['xtsjgzdx']['glgdbh'] = params['关联工单编号']
        json_str = json.dumps(data, ensure_ascii=False)
        base64_text = base64.b64encode(json_str.encode()).decode()
        json_data = {
            'defId': '2306291032256138203',
            'data': base64_text
        }
        response = ''
        try:
            response = self.session.post(
                f'https://{self.url}/runtime/runtime/instance/v1/start',
                headers=self.headers,
                json=json_data,
                verify=False, timeout=10)
            if response.json()['state']:
                self.log(response.json())
            else:
                _console(response.text)
                return False
        except Exception as e:
            _console(response.text)
            _console(e)


def main():
    y = yun_ge(_console)
    res = parse_event_text(text, _console)
    y.submit_ticket(res, sjclrID=_account)
